package com.yichat.micro.msghttpservice.common.result;

import com.yichat.micro.msghttpservice.common.vo.MsgHttpRequestVo;
import com.yichat.micro.msghttpservice.core.retry.RetryMsgHttpRequestVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;

import java.io.IOException;

/**
 * Created by chenmohan on 2019/03/28
 *
 * @description okHttpResult响应体
 */
@Data
@AllArgsConstructor
@Slf4j
public class OkHttpResult extends HttpResult {

    /*
    public static HttpResult resp(Response response) {
        int code = Constants.stauts_async;
        String msg = "";
        //如果头信息含有id,说明是异步请求
        String idString = response.header("id");
        Long id = null;
        if (StringUtil.isNotEmpty(idString)) {
            id = Long.valueOf(idString);
        }
        if ("1".equals(response.header("callbacked"))) {
            return new HttpResult(code, msg, "callback success", response.header("buz"), id);
        }
        if (response.header("sync") == null) {
            code = response.code();
            msg = StringUtil.isEmpty(response.message()) ? null : response.message();
            try {
                String body = response.body().string();
                Matcher m = p.matcher(body);
                body = m.replaceAll("");
                HttpResult buz = new HttpResult(code, msg, body, response.header("buz"), id);
                return buz;
            } catch (Exception e) {
                log.error("okHttp响应体转换String出错, response = {}", response.body(), e);
                return new HttpResult(code, msg, "数据出错", response.header("buz"), id);
            }
        } else {
            //将生成的id立即返回给调用方
            return new HttpResult(code, response.message(), null, response.header("buz"), id);
        }

    }

    */
    /*
    public static HttpResult resp(Response response) {
        String id = response.header("id");
        try {
            return new HttpResult(response.code(), response.message(), response.body().string(), response.header("buz"), StringUtil.isEmpty(id) ? null : Long.valueOf(response.header("id")));
        } catch (IOException e) {
            log.warn("[parse response body error]", e);
            return new HttpResult(response.code(), response.message(), "数据出错", response.header("buz"), Long.valueOf(response.header("id")));
        }
    }
    */
    public static HttpResult resp(Response response, RetryMsgHttpRequestVo retryVo) {
        MsgHttpRequestVo vo = retryVo.getVo();
        try {
            return new HttpResult(response.code(), response.message(), response.body().string(), vo.getBuz(), retryVo.getSid());
        } catch (IOException e) {
            log.warn("[parse response body error]", e);
            return new HttpResult(response.code(), response.message(), "数据出错", response.header("buz"), Long.valueOf(response.header("id")));
        }
    }
}
